package com.ytjj.qmyx.supplychain.service;

import com.ytjj.qmyx.supplychain.common.model.response.ShopInfoResponse;
import com.ytjj.qmyx.supplychain.mapper.ShopInfoMapper;
import com.ytjj.qmyx.supplychain.mapper.entity.YxShopInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class ShopInfoService {
    @Resource
    private ShopInfoMapper shopInfoMapper;

    public boolean insertByBean(YxShopInfo shopInfo) {
        if (null == shopInfo.getId()) {
            return shopInfoMapper.insertSelective(shopInfo) > 0 ? true : false;
        } else {
            return shopInfoMapper.updateByPrimaryKeySelective(shopInfo) > 0 ? true : false;
        }
    }

    public boolean updateStatus(Integer id, Integer status) {
        YxShopInfo shopInfo = shopInfoMapper.selectByPrimaryKey(id);
        if (null == shopInfo) {
            return false;
        }
        if (shopInfo.getStatus().equals(status)) {
            return false;
        }
        shopInfo.setStatus(status);
        shopInfoMapper.updateByPrimaryKey(shopInfo);
        return true;
    }

    public YxShopInfo queryShopInfoByPartnerId(String partnerId) {
        Example example = new Example(YxShopInfo.class);
        example.createCriteria().andEqualTo("parentId", partnerId);
        example.orderBy("id").desc();
        List<YxShopInfo> beans = shopInfoMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(beans)) {
            return null;
        }
        return beans.get(0);
    }

    public List<ShopInfoResponse> queryAllShopInfo() {
        Example example = new Example(YxShopInfo.class);
        example.orderBy("id").desc();
        List<YxShopInfo> shopInfoList = shopInfoMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(shopInfoList)) {
            return new ArrayList();
        }
        List<ShopInfoResponse> result = new ArrayList<>();
        shopInfoList.stream().forEach(item -> {
            ShopInfoResponse response = new ShopInfoResponse();
            BeanUtils.copyProperties(item, response);
            result.add(response);
        });
        return result;
    }
}
